package com.example.cachedemo;

import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public final class PhotoAdapter extends RecyclerView.Adapter<PhotoViewHolder> {
    private List<PhotoItem> items;
    public PhotoAdapter(List<PhotoItem> items) {
        this.items = items;
    }

    @NonNull
    @Override
    public PhotoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_photo, parent, false);
        final PhotoViewHolder holder = new PhotoViewHolder(view);
        // 点击事件
        ImageView imageView = holder.getPhotoImageView();
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int position = holder.getAdapterPosition();
                PhotoItem item = items.get(position);
                Toast.makeText(CacheDemoApplication.getContext(), "点击了图片:" + item.getName(), Toast.LENGTH_LONG).show();
            }
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull final PhotoViewHolder holder, int position) {
        PhotoItem item = items.get(position);
        String url = item.getImageUrl();
        String name = item.getName();
        holder.setName(name);
        BitmapLoader loader = BitmapLoader.getInstance();
        loader.loadBitmap(url, new BitmapLoader.BitmapLoaderCallback() {
            @Override
            public void success(Bitmap bitmap) {
                holder.setImage(bitmap);
            }

            @Override
            public void failure(String message) {
                // 什么也不做
            }
        });
    }

    @Override
    public int getItemCount() {
        return items.size();
    }
}
